package com.yaopaikeji.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.model.ContactUsInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
public class MailSendService {

    private static Logger logger = LoggerFactory.getLogger(MailSendService.class);
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Async
    public void sendContactUsMail(ContactUsInfo contactUsInfo,List<String> sendTos){

        if(sendTos == null || sendTos.isEmpty())
            return;

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message,false,"utf-8");
            helper.setFrom(Constants.SENDER_MAIL);
            helper.setTo((String[])sendTos.toArray());
            helper.setSubject(Constants.CONTACT_US_NOTIFY_SUBJECT);
            helper.setText(getMailHtml(contactUsInfo),true);

        } catch (MessagingException e) {

            logger.error("创建邮件失败"+contactUsInfo.toString(),e);

            return;
        }

        logger.info("开始发送邮件：" + message.toString());
        mailSender.send(message);
        try {
            logger.info("邮件发送完成，To:", JSONObject.toJSONString(message.getAllRecipients()));
        } catch (MessagingException e) {
            logger.error("获取收件方失败,message info:"+JSONObject.toJSONString(contactUsInfo));
        }
    }

    private String getMailHtml(ContactUsInfo contactUsInfo){

        Context context = new Context();
        context.setVariable("contactUsInfo",contactUsInfo);
        return templateEngine.process("contact_us_notify_mail",context);
    }


}
